<?php

/**
 * @notes 处理业务的类
 * @copyright: copyright 2018/1/6 all rights reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */

namespace app\online\controller;

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */

use app\common\model\Chatvisitor;
use app\common\model\ChatMessage;
use app\common\model\User;

use fast\Encrypt;
use GatewayWorker\Lib\Gateway;
use Workerman\Lib\Timer;
use fast\Tool;

class Events {

    public static function onWorkerStart($businessWorker) {
        if ($businessWorker->id == 0) {
        }
    }

    /**
     * @notes 有消息时
     * @author: xpz <496023850@qq.com>
     * @param $client_id
     * @param $message
     * @return null
     * @throws \Exception
     */
    public static function onMessage($client_id, $message) {
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id session:" . json_encode($_SESSION) . " onMessage:" . $message . "\r\n";
        $message_data = json_decode($message, TRUE);
        if (!$message_data) {
            return NULL;
        }


        
        $uuid = isset($message_data['uuid']) ? $message_data['uuid'] : 0;
        $token = isset($message_data['token']) ? $message_data['token'] : null;
        //验证token
        list($userId,$companyId) = Events::checkToken($token, $client_id);
//        echo "user_id".$userId." company_id".$companyId."\r\n";
        $message_data['user_id'] = $userId;
        $message_data['company_id'] = $companyId;

//        echo $admin_id."\r\n";
        //获取管理员信息
//        $adminRs = Events::checkKfIsValid($admin_id, $client_id);
//        $message_data['group_id'] = $group_id;
        switch ($message_data['type']) {
            // 客户端回应服务端的心跳
            case 'pong':
                break;
            case 'yk_login'://游客连接

                $_SESSION['uuid'] = $uuid;
                $_SESSION['uuid_user_id'] = $userId;
                $message_data['status'] = 1;

                //wrokerman绑定用户信息
                Gateway::bindUid($client_id, $uuid);
                Gateway::joinGroup($client_id, $userId);
                #更新用户上线
                Chatvisitor::updateOffOn($uuid, 1);
                #记录用户信息online_service_visitor
                Chatvisitor::Record($message_data);

                break;
            case 'yk_say'://游客发送信息
                #记录用户信息online_service_msg
                $message_data['user_id'] = $userId;
                $message_data['source_status'] = 1;
                $message_data['msg_status'] = 1;
                ChatMessage::Record($message_data);

                //给自己返回信息
                $time = date('H:i', time());
                $re_message['time'] = $time;
                $re_message['content'] = $message_data['content'];
                Events::returnMessage($client_id, 'yk_say_ok', '成功', 1,$re_message);
                //给客服发送信息
                if(!empty($userId) && !empty($companyId)){
//                    var_dump(Gateway::isUidOnline($userId));
                    if (Gateway::isUidOnline($userId)) {//客服在线
                        #客服在线，更新我发送的消息为已读
                        ChatMessage::updateMsg($uuid, $userId, 1);
                        $client_id_a = Gateway::getClientIdByUid($userId);
                        foreach ($client_id_a as $val) {
                            $re_message['time'] = $time;
                            $re_message['content'] = $message_data['content'];
                            $re_message['content_type'] = 1;
                            $re_message['from_uid'] = $uuid;
//                            $re_message['nickname'] = $res['nick_name'];
//                            $re_message['head_img'] = $res['head_img'];
                            $online_count = Gateway::getClientIdCountByGroup($userId);
                            $re_message['online_count'] = (int)($online_count - 1);
//                            var_dump($admin_id."当前在线人数");
//                            var_dump($online_count);
//                            var_dump($re_message);
                            Events::returnMessage($val, 'yk_send_ok', '成功', 1, $re_message);
                        }
                    } else {//微信通知客服
                        $re_message['time'] = $time;
                        //获取用户的openid
                        $userInfo = model("User")->where(['id'=>$userId])->find();
                        if(isset($userInfo['openid']) && !empty($userInfo['openid'])){
                            $loginToken = Tool::enLoginToken($userId, $userInfo['openid']);
                            $wxMessageNoticeRs = Tool::wxMessageNotice($userInfo['openid'], $re_message['content'], $uuid,$loginToken);
                            if($wxMessageNoticeRs == 'ok') { //客服在线
                                $re_message['content'] = '已经微信通知客服，请稍后！';
                            } else{
                                $re_message['content'] = '微信通知客服失败，请联系工作人员！';
                            }
                        } else {
                            $re_message['content'] = '当前客服不在线，待客服上线后为您处理问题！';
                        }
                        Events::returnMessage($client_id,'yk_say_ok', '成功', 1,$re_message);
                    }
                }

                break;
            case 'yk_close'://游客下线
                //游客状态修改为已下线
                Chatvisitor::updateOffOn($uuid, 2);
                Gateway::unbindUid($client_id, $uuid);
                unset($_SESSION['uuid']);
                unset($_SESSION['uuid_user_id']);
//                Gateway::sendToAll(json_encode(['type' => 'onclose']));
                Gateway::leaveGroup($client_id, $userId);
                break;
            case 'kf_login'://客服上线
                if (isset($userId) && $userId !== 'null') {
                    $_SESSION['user_id'] = $userId;
                    #更新管理员用户在线
                    User::updateOffOn($userId, 1);
//                        $_SESSION['admin_id'] = $admin_id;
                    Gateway::bindUid($client_id, $userId);
//                        Gateway::joinGroup($client_id, $group_id); //加入某个组
                    Gateway::joinGroup($client_id, $userId);
                    #广播通知大家(同一个组的)
                    $res_message['type'] = 'airing';
                    $res_message['user_id'] = $userId;
                    Gateway::sendToGroup($userId,json_encode($res_message));
                }
                
                break;
            case 'kf_say':
                #记录用户信息online_service_msg
                $message_data['source_status'] = 2;
                $res = ChatMessage::RecodeRet($message_data);
                $time = date('H:i', time());
                $re_message['time'] = $time;
                $re_message['content'] = $res['content'];
                Events::returnMessage($client_id, 'kf_say_ok', '成功', 1,$re_message);
                if ($res) {
//                    var_dump(Gateway::isUidOnline($uuid));
                    if (Gateway::isUidOnline($uuid)) {
                        #客户端在线 更新我发送的消息为已读
                        ChatMessage::updateMsg($uuid, $userId, 2);
                        $client_id_a = Gateway::getClientIdByUid($uuid);
                        foreach ($client_id_a as $val) {
                            $re_message['time'] = date('H:i', time());
                            $re_message['content'] = $res['content'];
                            Gateway::sendToClient($val, json_encode($re_message));
                            Events::returnMessage($val, 'kf_send_ok', '成功', 1,$re_message);
                        }
                    }
                }
                break;
            case 'kf_close':
                #更新管理员用户在线
                User::updateOffOn($userId, 2);
                Gateway::unbindUid($client_id, $userId);
//                Gateway::leaveGroup($client_id, $group_id);
                Gateway::leaveGroup($client_id, $userId);
                unset($_SESSION['user_id']);
                #广播通知大家
                $res_message['type'] = 'unairing';
                $res_message['user_id'] = $userId;
                Gateway::sendToGroup($userId,json_encode($res_message));
                break;
        }
        
        
    }
    
    

    

    
    public static function returnMessage($client_id,$type,$message,$code,$arr=[]){
        $re_message = $arr;
        $re_message['type'] = $type;
        $re_message['msg'] = $message;
        $re_message['code'] = $code;
        Gateway::sendToClient($client_id, json_encode($re_message));
        if($code == 0){
            return NULL; 
        }
        
    }
    
    public static function checkUuid($uuid,$client_id){
        $re_message = [];
        if(empty($uuid)){
            $re_message['type'] = 'error';
            $re_message['msg'] = "uuid 参数有误！";
            $re_message['code'] = 0;
            Gateway::sendToClient($client_id, json_encode($re_message));
            return NULL;  
        }
    }
    

    
    public static function checkToken($token,$client_id){
        $re_message = [];
        if(empty($token)){
            $re_message['type'] = 'error';
            $re_message['msg'] = "非法链接！";
            $re_message['code'] = 0;
            Gateway::sendToClient($client_id, json_encode($re_message));
            return NULL;  
        }
        
        $tokenArr = Tool::de_token($token);
        if(is_array($tokenArr) && count($tokenArr) == 2){
            return $tokenArr;
        } else {
            Events::returnMessage($client_id, 'error', '非法链接2', 0);
        }
    }



    /**
     * 当客户端断开连接时
     * @param integer $client_id 客户端id
     */
    public static function onClose($client_id) {
        if (isset($_SESSION['uuid'])) {
            $uuid = $_SESSION['uuid'];
            $userId = $_SESSION['uuid_user_id'];
            Chatvisitor::updateOffOn($uuid, 2);
            Gateway::unbindUid($client_id, $uuid);
            Gateway::sendToAll(json_encode(['type' => 'onclose']));
            Gateway::leaveGroup($client_id, $userId);
            unset($_SESSION['uuid']);
            unset($_SESSION['uuid_user_id']);
        }

        if (isset($_SESSION['user_id'])) {
            #更新用户离线
            $userId = $_SESSION['user_id'];
            User::updateOffOn($userId, 2);
            Gateway::unbindUid($client_id, $userId);
            unset($_SESSION['user_id']);
            $res_message['type'] = 'unairing';
            $res_message['user_id'] = $userId;
            Gateway::sendToAll(json_encode($res_message));
            Gateway::leaveGroup($client_id, $userId);
        }
//        Gateway::leaveGroup($client_id, $_SESSION['group_id']);
        //生产环境请注释
        echo "onClose : client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id\r\n";
    }

    /**
     * 客户端停止时批量下线
     * @param $businessWorker
     */
    public static function onWorkerStop($businessWorker) {
        //生产环境请注释
        //echo "WorkerStop\n";
        OnlineServiceVisitor::upStatusOff();
    }
  

}
